package com.jandan.ui.client;

import java.util.Iterator;

import java.util.List;
import java.util.Map;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.core.Position;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.SimpleStore;
import com.gwtext.client.data.Store;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Window;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.ComboBox;
import com.gwtext.client.widgets.form.FormPanel;
import com.gwtext.client.widgets.form.TextField;
import com.gwtext.client.widgets.form.ValidationException;
import com.gwtext.client.widgets.form.Validator;
import com.gwtext.client.widgets.form.event.ComboBoxListenerAdapter;
import com.gwtext.client.widgets.layout.FitLayout;
import com.jandan.ui.client.service.LessonService;
import com.jandan.ui.client.service.LessonServiceAsync;
import com.jandan.ui.client.service.WordLibService;
import com.jandan.ui.client.service.WordLibServiceAsync;
import com.jandan.ui.client.util.ClientUtil;
import com.jandan.ui.model.Lesson;
import com.jandan.ui.model.WordLib;

public class LessonWindow extends Window {
	private Lesson lesson = null;
	private ILessonOperator lessonOperator;

	public LessonWindow() {
		createComponent();
	}

	public LessonWindow(ILessonOperator lessonOperator) {// int lessonType){
		this.lessonOperator = lessonOperator;
		createComponent();
	}

	public LessonWindow(Lesson lesson) {
		this.lesson = lesson;
		createComponent();
	}

	private void createComponent() {
		this.setTitle("新建课程");
		this.setWidth(400);
		this.setHeight(250);
		this.setResizable(false);
		this.setLayout(new FitLayout());
		this.setPaddings(5);
		this.setCloseAction(Window.CLOSE);
		this.setPlain(true);
		this.setModal(true);

		// create the form
		final FormPanel formPanel = new FormPanel();
		formPanel.setFrame(true);
		formPanel.setPaddings(5, 5, 5, 0);
		formPanel.setWidth(350);
		formPanel.setLabelWidth(95);
		formPanel.setLabelAlign(Position.RIGHT);

		final TextField lessonName = new TextField("课程名称", "lessonName", 210);

		lessonName.setAllowBlank(false);
		if (lesson != null) {
			lessonName.setDisabled(true);
		}
		lessonName.setValidator(new Validator() {

			public boolean validate(String value) throws ValidationException {
				// TODO Auto-generated method stub
				if (value != null && value.trim().length() > 0) {
					Map<Long, String> map = lessonOperator.getLessons();
					Iterator<String> it = map.values().iterator();
					while (it.hasNext()) {
						String l = it.next();
						if (l.equalsIgnoreCase(value.trim())){
							lessonName.setInvalidText("此课程名已被使用");
							return false;
						}
						
					}
				}
				return true;
			}
		});

		formPanel.add(lessonName);

		final ComboBox libNameComboBox = new ComboBox();
		libNameComboBox.setForceSelection(true);
		libNameComboBox.setMinChars(1);
		libNameComboBox.setFieldLabel("词库");
		libNameComboBox.setDisplayField("wordLibName");
		libNameComboBox.setValueField("wordLibID");
		libNameComboBox.setMode(ComboBox.LOCAL);
		libNameComboBox.setTriggerAction(ComboBox.ALL);
		libNameComboBox.setTypeAhead(true);
		libNameComboBox.setSelectOnFocus(true);
		libNameComboBox.setEmptyText("请选择词库");
		libNameComboBox.setWidth(150);
		libNameComboBox.setEditable(false);
		libNameComboBox.setHideTrigger(false);
		libNameComboBox.setAllowBlank(false);
		libNameComboBox.setBlankText("词库名不能为空");
		libNameComboBox.setReadOnly(true);

		formPanel.add(libNameComboBox);

		final ComboBox wordsCountOfPerSmallLibComboBox = new ComboBox();
		wordsCountOfPerSmallLibComboBox.setForceSelection(true);
		wordsCountOfPerSmallLibComboBox.setMinChars(1);
		wordsCountOfPerSmallLibComboBox.setFieldLabel("小词库单词数");
		wordsCountOfPerSmallLibComboBox
				.setDisplayField("wordsCountOfPerSmallLib");
		wordsCountOfPerSmallLibComboBox
				.setValueField("wordsCountOfPerSmallLib");
		wordsCountOfPerSmallLibComboBox.setMode(ComboBox.LOCAL);
		wordsCountOfPerSmallLibComboBox.setTriggerAction(ComboBox.ALL);
		wordsCountOfPerSmallLibComboBox.setTypeAhead(true);
		wordsCountOfPerSmallLibComboBox.setSelectOnFocus(true);
		wordsCountOfPerSmallLibComboBox.setEmptyText("请选择小词库单词数");
		wordsCountOfPerSmallLibComboBox.setWidth(150);
		wordsCountOfPerSmallLibComboBox.setLinked(true);
		wordsCountOfPerSmallLibComboBox.setEditable(false);
		wordsCountOfPerSmallLibComboBox.setHideTrigger(false);
		wordsCountOfPerSmallLibComboBox.setAllowBlank(false);
		wordsCountOfPerSmallLibComboBox.setBlankText("小词库单词数不能为空");
		wordsCountOfPerSmallLibComboBox.setReadOnly(true);
		wordsCountOfPerSmallLibComboBox.setForceSelection(true);
//		wordsCountOfPerSmallLibComboBox.setValue("30");
//		wordsCountOfPerSmallLibComboBox.setHideLabel(true);
//		wordsCountOfPerSmallLibComboBox.setVisible(false);

		formPanel.add(wordsCountOfPerSmallLibComboBox);

		WordLibServiceAsync wordLibService = WordLibService.Util.getInstance();
		wordLibService.getWordLibList(new AsyncCallback<List<WordLib>>() {
			public void onFailure(Throwable caught) {
				MessageBox.alert(caught.getMessage());
			}

			public void onSuccess(List<WordLib> result) {
				// TODO Auto-generated method stub
				final Store libNameStore = new SimpleStore(new String[] {
						"wordLibID", "wordLibName" }, getWordLibName(result));
				libNameStore.load();
				libNameComboBox.setStore(libNameStore);

				final Store wordsCountOfPerSmallLibStore = new SimpleStore(
						new String[] { "wordLibID", "wordsCountOfPerSmallLib" },
						getWordsCountOfPerSmallLib(result));
				wordsCountOfPerSmallLibStore.load();
				wordsCountOfPerSmallLibComboBox
						.setStore(wordsCountOfPerSmallLibStore);

				libNameComboBox.addListener(new ComboBoxListenerAdapter() {
					public void onSelect(ComboBox comboBox, Record record,
							int index) {
						wordsCountOfPerSmallLibComboBox.setValue("");
						wordsCountOfPerSmallLibStore.filter("wordLibID",
								comboBox.getValue());
					}
				});
			}
		});

		final TextField newWordsCountOfPerTurnField = new TextField("每一轮单词数",
				"numberOfOnceTimeStudy", 210);
		newWordsCountOfPerTurnField.setValue("10");
		newWordsCountOfPerTurnField.setAllowBlank(false);
		newWordsCountOfPerTurnField.setBlankText("每轮学习单词数不能为空");
//		newWordsCountOfPerTurnField.setHideLabel(true);
//		newWordsCountOfPerTurnField.setVisible(false);
		newWordsCountOfPerTurnField.setValidator(new Validator() {
			public boolean validate(String value) throws ValidationException {
				// TODO Auto-generated method stub
				// 这个值必须大于7小于30
				int v = Integer.parseInt(value);
				//!value.matches("^[0-9]*[1-9][0-9]*$") || 
				if(v < 7 || v > 30){
					newWordsCountOfPerTurnField
							.setInvalidText("必须输入7到30之间的数字(含7和30)");
					return false;
				}
				return true;
			}
		});
		formPanel.add(newWordsCountOfPerTurnField);
		formPanel.setButtonAlign(Position.RIGHT);

		Button ok = new Button("确定");
		Button cancel = new Button("取消");

		ok.addListener(new ButtonListenerAdapter() {
			@Override
			public void onClick(Button button, EventObject e) {
				// TODO Auto-generated method stub
				if (formPanel.getForm().isValid()) {
					Map<String, String> formData = ClientUtil
							.getFormDataAsMap(formPanel.getForm());

					String lessonName = formData.get("lessonName");
					long wordLibID = Long.parseLong(libNameComboBox.getValue());
					int wordsCountOfPerSmallLib = Integer
							.parseInt(wordsCountOfPerSmallLibComboBox
									.getValue());
					int newWordsCountOfPerTurn = Integer
							.parseInt(newWordsCountOfPerTurnField.getText());

					// 插入，返回lesson,如果成功的话则直接添加到
					final Lesson lesson = new Lesson();
					lesson.setLessonName(lessonName);
					lesson.setWordLibID(wordLibID);
					lesson.setWordsCountOfPerSmallLib(wordsCountOfPerSmallLib);
					lesson.setNewWordsCountOfPerTurn(newWordsCountOfPerTurn);
					LessonServiceAsync lessonService = LessonService.Util
							.getInstance();
					lessonService.insertLesson(lesson,
							new AsyncCallback<Lesson>() {

								public void onFailure(Throwable caught) {
									// TODO Auto-generated method stub
									MessageBox.alert("添加课程错误");
								}

								public void onSuccess(Lesson result) {
									// TODO Auto-generated method stub
									if (result != null) {
										lessonOperator.addLesson(result);
									}
								}
							});
					closeTheWindow();
				}
			}
		});

		cancel.addListener(new ButtonListenerAdapter() {
			@Override
			public void onClick(Button button, EventObject e) {
				// TODO Auto-generated method stub
				// super.onClick(button, e);
				closeTheWindow();
			}
		});
		
		formPanel.addButton(ok);
		formPanel.addButton(cancel);
		
		this.add(formPanel);
	}

	private Object[][] getWordLibName(List<WordLib> wordLibList) {
		Object[][] wordLibs = new Object[wordLibList.size()][];

		int size =  wordLibList.size(); 
		for (int i = 0; i < size; i++) {
			wordLibs[i] = new Object[] { wordLibList.get(i).getWordLibID(),
					wordLibList.get(i).getWordLibName() };
		}
		return wordLibs;
	}

	private Object[][] getWordsCountOfPerSmallLib(List<WordLib> wordLibList) {
		Object[][] wordsCountOfPerSmallLibs = new Object[wordLibList.size() * 4][];
		WordLib wordLib = null;
		for (int i = 0, n = wordLibList.size(); i < n; i++) {
			wordLib = wordLibList.get(i);
			wordsCountOfPerSmallLibs[i * 4] = new Object[] {
					wordLib.getWordLibID(), wordLib.getFirstClass() };
			wordsCountOfPerSmallLibs[i * 4 + 1] = new Object[] {
					wordLib.getWordLibID(), wordLib.getSecondClass() };
			wordsCountOfPerSmallLibs[i * 4 + 2] = new Object[] {
					wordLib.getWordLibID(), wordLib.getThirdClass() };
			wordsCountOfPerSmallLibs[i * 4 + 3] = new Object[] {
					wordLib.getWordLibID(), wordLib.getForthClass() };
		}

		return wordsCountOfPerSmallLibs;
	}

	private void closeTheWindow() {
		this.close();
	}
}
